import Radio from 'backbone.radio';
import {
    strToFloat,
    getTvaPart,
    htFromTtc,
    formatAmount,
} from '../../math.js';
import BaseModel from '../../base/models/BaseModel.js';

const DiscountModel = BaseModel.extend({
    props: [
        'id',
        'amount',
        'tva',
        'ht',
        'description',
        'mode',
    ],
    validation: {
        description: {
            required: true,
            msg: "Remise : Veuillez saisir un objet",
        },
        amount: {
            required: true,
            pattern: "amount",
            msg: "Remise : Veuillez saisir un coût unitaire, dans la limite de 5 chiffres après la virgule",
        },
        tva: {
            required: true,
            pattern: "number",
            msg: "Remise : Veuillez sélectionner une TVA"
        },
    },
    /**
     * 
     * @returns default tva and mode retrieved from config and user session
     */
    defaults: function () {
        const result = {};
        const config = Radio.channel('config')
        result['mode'] = config.request('get:options', 'compute_mode');

        const defaults = config.request('get:options', 'defaults');
        const default_tva = defaults['tva'];

        const user_session = Radio.channel('session');
        result['tva'] = user_session.request('get', 'tva', default_tva);
        return result;
    },
    initialize() {
        this.user_session = Radio.channel('session');
        this.on('saved', this.onSaved, this);
        this.user_preferences = Radio.channel('user_preferences');
    },
    onSaved() {
        this.user_session.request('set', 'tva', this.get('tva'));
        this.user_session.request('set', 'product_id', this.get('product_id'));
    },
    ht: function () {
        if (this.get('mode') == 'ht') {
            return -1 * strToFloat(this.get('amount'));
        } else {
            return htFromTtc(this.ttc(), this.tva_value());
        }

    },
    tva_value: function () {
        var tva = this.get('tva');
        if (tva < 0) {
            tva = 0;
        }
        return tva;
    },
    tva: function () {
        return getTvaPart(this.ht(), this.tva_value());
    },
    ttc: function () {
        if (this.get('mode') == 'ht') {
            return this.ht() + this.tva();
        } else {
            return -1 * strToFloat(this.get('amount'));
        }
    },
    amount_label() {
        let result;
        if (this.get('mode') === 'ht') {
            result = this.user_preferences.request('formatAmount', this.ht(), false);
        } else {
            result = this.user_preferences.request('formatAmount', this.ttc(), false);
        }
        return result;
    }
});
export default DiscountModel;